package com.powernode.web.handle;

import com.powernode.exceptions.BossException;
import com.powernode.web.result.CommonResult;
import com.powernode.web.result.RespCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @RestControllerAdvice 是 @ControllerAdvice 和 @ResponseBody 的结合
 * @ControllerAdvice 标注该类可以为所有的 @RequestMapping 处理方法提供异常处理，和 @ExceptionHandler 组合使用
 * 使用slf4j的LoggerFactory.getLogger打印处理异常的日志
 */
@RestControllerAdvice
public class RequestExceptionHandle {

    private Logger logger = LoggerFactory.getLogger(RequestExceptionHandle.class);

    // 处理Bean Validation BindException异常
    @ExceptionHandler({BindException.class})
    public CommonResult handleBindException(BindException bind) {
        // 拼接异常信息，作为返回data
        StringBuffer buffer = new StringBuffer();
        // 获取所有异常结果(所有属性)
        BindingResult br = bind.getBindingResult();
        List<FieldError> fieldErrors = br.getFieldErrors();
        int index = 0;
        for (FieldError error : fieldErrors) {
            buffer.append(++index)
                    .append(".错误项：").append(error.getField())
                    .append(",原因：").append(error.getDefaultMessage())
                    .append("; ");
        }
        logger.error("请求参数异常BindException:{}", buffer.toString());
        return new CommonResult(400, "请求参数不符合要求", buffer);
    }

    // 处理自定义BossException异常
    @ExceptionHandler({BossException.class})
    public CommonResult handleBossException(BossException boss) {
        RespCode respCode = boss.getRespCode();
        logger.error("登录异常BossException:{}", respCode.getCode());
        return new CommonResult(respCode.getCode(), respCode.getText(), "");
    }
}
